﻿package src.model 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * 数据模型
	 * 
	 * @author	MeatHill
	 * @version	0.1(2009-06-02)
	 */
	public class data_model extends EventDispatcher
	{
		private var _data_xml:XML;
		private var _xml_loader:URLLoader;
		private var _xml_url:URLRequest;
		
		public function data_model(url:String = '') 
		{
			_xml_loader = new URLLoader();
			_xml_loader.addEventListener(Event.COMPLETE, load_complete);
			_xml_loader.addEventListener(IOErrorEvent.IO_ERROR, load_failed);
			
			if (url) {
				_xml_url = new URLRequest(url);
			}
		}
		
		/***************
		 * properties
		 * ************/
		public function get pro_name():String {
			return _data_xml.@name;
		}
		public function get part_num():uint {
			return _data_xml.part.length();
		}
		public function get part_data():XMLList {
			return _data_xml.part;
		}
		public function get menu_data():XMLList {
			return _data_xml.menu.children();
		}
		
		/***************
		 * functions
		 * ************/
		private function load_complete(evt:Event):void {
			_data_xml = XML(_xml_loader.data);
			
			_xml_loader.removeEventListener(Event.COMPLETE, load_complete);
			_xml_loader.removeEventListener(IOErrorEvent.IO_ERROR, load_failed);
			_xml_loader = null;
			
			var _evt:Event = new Event(Event.COMPLETE);
			dispatchEvent(_evt);
		}
		private function load_failed(evt:IOErrorEvent):void {
			trace("load failed..");
			var _evt:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR);
			dispatchEvent(_evt);
		}
		
		/****************
		 * methods
		 * *************/
		public function load(url:String = ''):void {
			if (url) {
				_xml_url = new URLRequest(url);
			}
			if (_xml_url) {
				_xml_loader.load(_xml_url);
			}
		}
		public function get_part_size_by_index(index:uint):Object {
			var _part:XML = _data_xml.part[index];
			return { w:uint(_part.@width), h:uint(_part.@height), l:uint(_part.@length) };
		}
		public function get_part_face_by_name(pi:uint, name:String):String {
			return _data_xml.part[pi].face.(@name == name).@src;
		}
    public function get_target_player(id:String):XML {
      return _data_xml..screen.(@id == id)[0];
    }
	}
}